<template>
  <div class="addallot">
        <div class="top-add">
            <div style="width:80%">
              <el-page-header @back="backOutStore" content="新增调拨单"></el-page-header>
            </div>
            <div style="width:300px">
                 <el-button size="mini" type="primary" @click="selectProd">选择装备</el-button>
                <el-button size="mini" type="primary" @click="allotSave">保存</el-button>
                <!-- <el-button size="mini" type="primary" @click="backOutStore">取消</el-button> -->
            </div>
            
            
        </div>
      <el-row :gutter="16" style="line-height:40px;margin-top:-20px;margin-bottom:20px">
        <el-col :span="4">
          <div class="">
            <label for="">调拨单号</label>
            <el-input v-model="allot_num" size="small" disabled placeholder="可自动生成" style="width:80%"></el-input>
          </div>
        </el-col>

         <el-col :span="4">
          <div>
            <label for="">调拨仓库</label>
            <div class="main-content">
              <el-select v-model="allot_store" placeholder="请选择" @change="selectStore($event)" style="width:80%"  size="small">
                <el-option
                  v-for="item in storelist"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId">
                </el-option>
              </el-select>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div class="">
            <label for="">制单人</label>
            <el-input v-model="allot_person" size="small" style="width:80%"></el-input>
          </div> 
        </el-col>
        <el-col :span="4">
          <div class="">
            <label for="">调拨日期</label>
            <div>
              <el-date-picker  style="width:80%" size="small" 
                type="date" placeholder="选择日期" 
                v-model="allot_date">
              </el-date-picker>
            </div>
          </div> 
        </el-col>

        <el-col :span="4">
            <label for="">备注</label>
            <el-input v-model="allot_remark" size="small" placeholder="" style="width:90%"></el-input>
        </el-col>

      </el-row>

      <el-row>
        <el-col :span="24">
          <el-table :data="allotSelectProd" border style="width: 100%">
            <el-table-column label="图片" width="60">
              <template slot-scope="scope">
                <div>
                  <img style="width:40px;height:40px;" :src="scope.row.prodImg" alt="">
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="categoryTwoName" label="装备细类"></el-table-column>
            <el-table-column prop="prodCode" label="装备编号" width="120"></el-table-column>
            <el-table-column prop="prodName" label="装备名称" width="120"></el-table-column>
            <el-table-column prop="prodSpecial" label="规格" width="80"></el-table-column>
            <el-table-column prop="prodResiduenum" label="可出库数"></el-table-column>
            <el-table-column prop="prodNum" label="调拨数">
              <template slot-scope="scope">
                <div>
                  <el-input onkeyup="value=value.replace(/[^\d]/g,'')" size="mini" 
                    v-model="scope.row.prodNum" @input="changeNums($event,scope.row)"
                    placeholder="请输入数字"
                  ></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="emit" label="单位"></el-table-column>
            <!-- <el-table-column prop="prodPrice" label="价格"></el-table-column> -->
            <el-table-column prop="areaName" label="库区"></el-table-column>
            <el-table-column prop="departmentCode" label="库位"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" icon="el-icon-delete" @click="delSelectProd(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      

      <div class="autospace"></div>

      <selectstock :selectprodDialog.sync="selectprodDialog"></selectstock>
  </div>
</template>

<script>
import selectstock from '@/components/selectStock';
import { GetStore } from '@/api/store';
import { AllotStore, FindAllotOrderById, UpdateAllotOrder } from '@/api/allot';
import { getStore } from '@/utils/app.js';
export default {
  name: 'addallot',
  components: {
    selectstock
  },
  data() {
    return {
        selectprodDialog: false, // 打开选择商品弹框
        is_search: false,
        allot_num: '',
        allot_type: '',
        allot_store: '',
        allot_person: '',
        allot_date: new Date(),
        allot_remark: '',
        allotId: null,
        allotSelectProd: [
           
        ],
        storelist: [],
        updateAllotprod: []
    }
    
  },
  computed: {
    storeid() {
      return this.$store.state.store.store_id || getStore();
    },
    main_store() {
      return this.$store.state.store.main_store;
    },
    getSelectprod() {
      return this.$store.state.ware.selectProds;
    }
  },
  watch: {
    storeid(newVal) {
      if (newVal) {
        this.getStorelist()
      }
    },
    selectprodDialog(newVal) {
      if (!newVal) {
        if (this.getSelectprod.length != 0) {
          this.getSelectprod.forEach(e => e.type = 'add')
        }

        let newArr = this.allotSelectProd.concat(this.getSelectprod);
        this.newSelect = JSON.parse(JSON.stringify(newArr));
        for( let n = 0; n < this.newSelect.length; n++) {        
          this.newSelect[n].edit_id = n + 1;
        }
        // 去除里面重复的商品
        this.allotSelectProd = this.newSelect.filter((item, index, origin) => 
          index === origin.findIndex(itemInner => {
            return itemInner.stockId === item.stockId
          }
        ))
        // console.log(this.allotSelectProd)
      }
    }
  },
  methods:{
    selectStore(value) {
      if (value == this.storeid) {
        this.$message({
          message: '请选择其他仓库',
          type: 'warning'
        })
      }
    },
    getStorelist() {
      GetStore().then( res => {
        this.storelist = res.data;
        this.storelist = this.storelist.filter(e => e.warehouseId != this.storeid);
      })
    },
    // 去选择商品
    selectProd() {
      this.selectprodDialog = true;
    },
    backOutStore() {
        this.$router.push('/allot')
    },
    // 输入调拨数时进行判断
    changeNums(value,item) {
      let newStock = parseInt(item.prodResiduenum);
      let newVal = parseInt(value);
      let ifTrue = newStock - newVal;
      if (ifTrue < 0) {
        this.$message({
          message: '库存数不足,请重新输入',
          type: 'warning'
        })
        item.prodNum = ""
      }
      if (item.type == 'add') {
        return
      } else {
        item.type = 'edit'
      }
    },
    delSelectProd(el) {
      if (this.allotId) {
        if (el.type == 'add') {
          this.allotSelectProd = this.allotSelectProd.filter( e => e.edit_id != el.edit_id);
        } else {
          let currentDelete = this.allotSelectProd.filter( e => e.stockId == el.stockId);
          let currentTwo = {
            allotdetailsId: currentDelete[0].allotdetailsId,
            allotId:  this.allotId,
            prodNum: currentDelete[0].prodNum,
            stockId: currentDelete[0].stockId,
            type: 'delete'
          }
          // currentDelete[0].type = 'delete';
          this.updateAllotprod.push(currentTwo)
          this.allotSelectProd = this.allotSelectProd.filter( e => e.edit_id != el.edit_id);
        }
      } else {
        this.allotSelectProd = this.allotSelectProd.filter( e => e.edit_id != el.edit_id);
      }
      
    },
    // 更新仓库
    updateAllotStore() {
      let reqData = {
        allotId: this.allotId,
        allotNum: this.allot_num,
        allotDate: this.allot_date,
        allotWarehouseid: this.allot_store,
        allotPerson: this.allot_person,
        allotRemark: this.allot_remark,
        list: this.updateAllotprod,
      }
      console.log(reqData)
      UpdateAllotOrder(reqData).then( res => {
        this.$message({
          message: res.data.msg,
          type: 'success'
        })
        setTimeout(() => {
          this.$router.push('/allot')
        }, 1000)
      }).catch( error => console.log(error))
    },
    // 新增保存
    addAllotStore() {
      let reqData = {
        allotNum: this.allot_num,
        allotDate: this.allot_date,
        allotWarehouseid: this.allot_store,
        allotPerson: this.allot_person,
        allotRemark: this.allot_remark,
        aorderPutProds: this.allotSelectProd,
      }
      // console.log(reqData)
      AllotStore(reqData).then( res => {
        this.$message({
          message: res.data.msg,
          type: 'success'
        })
        setTimeout(() => {
          this.$router.push('/allot')
        }, 1000)
      }).catch( error => console.log(error))
    },
    // 调拨保存
    allotSave() {
      if (!this.allot_store) {
        this.$message({
          message: '请选择调拨仓库',
          type: 'warning'
        })
      } else {
        if (this.allotSelectProd.length == 0) {
          this.$message({
            message: '请选择调拨装备',
            type: 'warning'
          })
        } else {
            let arrOut = this.allotSelectProd.filter( el => {    // 未输入调拨数的装备
              if (!el.prodNum) {
                return el
              }
            })

            let editout = this.allotSelectProd.filter( el => {    // 过滤修改后的装备
              if (el.type == 'edit') {
                return el
              }
            })
            let addout = this.allotSelectProd.filter( el => {    // 过滤新增的装备
              if (el.type == 'add') {
                return el
              }
            })
            let editoutTwo = []
            editout.forEach(el => {
              let currentTwo = {
                allotdetailsId: el.allotdetailsId,
                allotId:  this.allotId,
                prodNum: el.prodNum,
                stockId: el.stockId,
                type: 'edit'
              }
              editoutTwo.push(currentTwo)
            })
            // 对新增装备重置类型
            addout.forEach(el => {
              let addTow = {
                allotdetailsId: '',
                allotId:  this.allotId,
                prodNum: el.prodNum,
                stockId: el.stockId,
                type: el.type
              }
              this.updateAllotprod.push(addTow)
            })
            this.updateAllotprod = this.updateAllotprod.concat(editoutTwo)

            if (arrOut.length != 0) {
              this.$message({
                message: '请输入调拨数',
                type: 'warning'
              })
            } else {
     
              this.allot_date = this.formatDate(this.allot_date);
              if (this.allotId) {
                this.updateAllotStore()
              } else {
           
                this.addAllotStore()
              }
            }
        }
        
      } 
    }
  },

  mounted() {
    // 获取所有仓库
    this.getStorelist()

    this.allotId = this.$route.query.allotId;
    if (this.allotId) {
      FindAllotOrderById(this.allotId).then( res => {
        let orderDetail = res.data[0];
        orderDetail.allotDate = this.formatDate(orderDetail.allotDate);
        this.allot_num = orderDetail.allotNum;
        this.allot_date = orderDetail.allotDate;
        this.allot_store = orderDetail.allotWarehouseid;
        this.allot_person = orderDetail.allotPerson;
        this.allot_remark = orderDetail.allotRemark;

        if (orderDetail.aorderPutProds && orderDetail.aorderPutProds.length != 0) {
          this.allotSelectProd = orderDetail.aorderPutProds;

          for( let n = 0; n < this.allotSelectProd.length; n++) {        
            this.allotSelectProd[n].edit_id = n + 1;
          }
        }
        
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/config.scss';

  .label-wrap {
    &.category { @include labelwrap(left,100,40); }
    &.date {
      @include labelwrap(center,50,40); }
    &.keyword { @include labelwrap(right,110,40); }
  }
  .autospace {
    height: 30px;
  }
  
  .top-add {
    width: 100%;
    height: 40px;
    margin-bottom: 20px;
    // font-weight: 700;
    border-bottom: 1px solid #f1f1f1;
    display: flex;
  }
</style>
  
